<template>
  <div class="login">
    <div class="login-box">
      <div class="login-title">商城后台管理系统</div>
      <el-form
        class="login-form"
        :model="userinfo"
        :rules="rules"
        ref="loginFrom"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="shop shop-yonghu"
            v-model="userinfo.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="shop shop-tianchongxing-"
            v-model="userinfo.password"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { login } from '../../api/user'
export default {
  name: 'Login',
  data() {
    return {
      userinfo: {
        // 登录表单绑定数据
        username: 'admin',
        password: '123456'
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在3到10个字符之间',
            tirgger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度最小为6位', tirgger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login() {
      this.$refs.loginFrom.validate(valid => {
        if (valid) {
          login(this.userinfo).then(res => {
            if (res.meta.status === 200) {
              this.$store.commit('setToken', res.data.token)
              this.$message({
                message: res.meta.msg,
                type: 'success',
                duration: 3000
              })
              this.$router.push('/home')
            } else {
              this.$message({
                message: res.meta.msg,
                type: 'error',
                duration: 3000
              })
            }
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scope>
.login {
  height: 100%;
  background-color: #2b4b6b;
  .login-box {
    position: absolute;
    top: 50%;
    left: 50%;
    padding: 20px;
    width: 450px;
    height: 300px;
    transform: translate(-50%, -50%);
    background-color: #fff;
    border-radius: 5px;
    box-sizing: border-box;
    .login-title {
      padding: 20px;
      font-size: 32px;
      font-weight: 500;
      text-align: center;
    }
    .login-form {
      margin-top: 10px;
    }
    .el-button {
      width: 100%;
    }
  }
}
</style>
